package com.adamall.controller;

import com.adamall.dao.ShopMapper;
import com.adamall.dao.UserMapper;
import com.adamall.module.ShopExample;
import com.adamall.module.User;
import com.adamall.module.UserExample;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/api/v1")


public class User_Controller {

    public static Map<String, Boolean> VerificationCode = new HashMap<>();

    @Autowired
    UserMapper userMapper;
    UserExample userExample;
    UserExample.Criteria criteria;

    //登入
    @PostMapping("login")
    public ResponseEntity<String> login(@RequestBody Map<String, String> login, HttpSession httpSession) {

        AuthenticationToken token = new UsernamePasswordToken(login.get("tel"), login.get("code"));
        Subject subject = SecurityUtils.getSubject();
        HttpHeaders headers = new HttpHeaders();
        if (VerificationCode.get(login.get("tel")) == null || !VerificationCode.get(login.get("tel"))) {
            headers.set("Custom-Header", "不先发送验证码，无法登录");
            return ResponseEntity.status(400).headers(headers).body("请先发送验证码");
        } else {
            try {
                subject.login(token);
                httpSession.setAttribute("JSESSIONID", login.get("tel"));
                headers.set("Custom-Header", "登录成功");
                return ResponseEntity.status(200).headers(headers).body("ok");
            } catch (UnknownAccountException | IncorrectCredentialsException e) {
                headers.set("Custom-Header", "密码错误，无法登录");
                return ResponseEntity.status(400).headers(headers).body("no");
            }
        }
    }

    //登出
    @PostMapping("/logout")
    public ResponseEntity<String> logout(HttpSession httpSession) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            //清除验证码
            VerificationCode.put(String.valueOf(getCurrentUser().getTel()), false);
            subject.logout();

        }

        return ResponseEntity.ok().header("Custom-Header", "成功登出").body("成功登出");
    }

    //获取验证码
    @PostMapping("request-sms-code")
    public ResponseEntity<String> code(@RequestBody Map<String, String> code) {
        VerificationCode.put(code.get("tel"), true);
        return ResponseEntity.ok().header("Custom-Header", "成功获取验证码").body("成功获取验证码");
    }

    @RequiresAuthentication
    @GetMapping("me")
    public ResponseEntity<Object> me(HttpServletRequest request) {
        String tel = (String) request.getSession().getAttribute("JSESSIONID");
        if (!tel.isEmpty()) {
            userExample = new UserExample();
            criteria = userExample.createCriteria();

            criteria.andTelEqualTo(tel);
            User user = userMapper.selectByExample(userExample).get(0);
            return ResponseEntity.ok().header("Custom-Header", "访问me").body(Response_login.of(true, user));
        }

        return ResponseEntity.status(401).header("Custom-Header", "Unauthorized").body("Unauthorized");
    }

    @PutMapping("me")
    public ResponseEntity<Object> UpdateInformation(@RequestBody Map<String, String> information) {
        User user = getCurrentUser();
        user.setName(information.get("name"));
        user.setAddress(information.get("address"));
        userMapper.updateByExampleSelective(user, userExample);

        return ResponseEntity.status(200).header("Custom-Header", "Status code is 200").body("");

    }


    //获取用户
    public User getCurrentUser() {
        return (User) SecurityUtils.getSubject().getPrincipal();
    }

}
